package com.msb.apidriver.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.msb.commons.constant.TokenConstant;
import com.msb.commons.response.ResponseResult;
import com.msb.commons.response.TokenResult;
import com.msb.commons.util.JwtUtils;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Author: chshh
 * @version: 1.0
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean result = true;
        String resultString = "";

        //解析token
        String token = request.getHeader("Authorization");
        TokenResult tokenResult = null;

        try {
            tokenResult = JwtUtils.parseToken(token);
        }catch (SignatureVerificationException e){
            resultString = "SignatureVerificationException";
            result = false;
        }catch (TokenExpiredException e){
            resultString = "TokenExpiredException";
            result = false;
        }catch (AlgorithmMismatchException e){
            resultString = "AlgorithmMismatchException";
            result = false;
        }catch (Exception e){
            resultString = "Exception";
            result = false;
        }

        if(tokenResult == null){
            resultString = "Exception";
            result = false;
        }else {
            //拼接Key
            String phone = tokenResult.getPhone();
            String identity = tokenResult.getIdentity();
            String tokenKey = TokenConstant.ACCESS_TOKEN_TYPE+phone+identity;

            //从redis中取出token
            String tokenRedis = stringRedisTemplate.opsForValue().get(tokenKey);
            if(StringUtils.isBlank(tokenRedis)){
                resultString = "Exception";
                result = false;
            }else {//比较我们传入的token和redis中的token是否相等
                if(!token.trim().equals(tokenRedis.trim())){
                    resultString = "Exception";
                    result = false;
                }
            }
        }

        if(!result){
            PrintWriter writer = response.getWriter();
            //JSONObject.fromObject()  转换为json类型
            writer.println(JSONObject.fromObject(ResponseResult.fail(resultString)).toString());
        }

        return result;
    }
}
